<?php

/**
 * 文件上传 - 管理后台
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\admin\controller;

use app\admin\Controller;
use think\Db;

class Upload extends Controller
{

    /**
     * 首页
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 文件上传
     */
    public function upload()
    {
        $files = $this->request->file('file');
        $insert = [];
        $save_root = "images/" . date("Y/m-d/");
        foreach ($files as $file) {
            $path = ROOT_PATH . 'public/uploads/' . $save_root;
            $info = $file->rule('uniqid')->move($path, true);
            if ($info) {
                $data[] = $this->request->root() . '/uploads/' . $save_root . $info->getSaveName();
                $insert[] = [
                    'cate' => 0,
                    'name' => $data[] = $this->request->root() . '/uploads/' . $save_root. $info->getSaveName(),
                    'original' => $info->getInfo('name'),
                    'domain' => '',
                    'type' => $info->getInfo('type'),
                    'size' => $info->getInfo('size'),
                    'mtime' => time(),
                ];
            } else {
                $error[] = $file->getError();
            }
        }
        Db::name('File')->insertAll($insert);

        return ajax_return($data);
    }

    /**
     * 远程图片抓取
     */
    public function remote()
    {
        $url = $this->request->post('url');
        $save_root = "images/" . date("Y/m-d/");
        // validate
        $name = ROOT_PATH . 'public/uploads/' . $save_root . get_random();
        $name = \File::downloadImage($url, $name);

        $ret = $this->request->root() . '/uploads/' . $save_root . basename($name);

        return ajax_return(['url' => $ret], '抓取成功');
    }

    /**
     * 图片列表
     */
    public function listImage()
    {
        $page = $this->request->param('p', 1);
        if ($this->request->param('count')) {
            $ret['count'] = Db::name('File')->where('cate=0')->count();
        }
        $ret['list'] = Db::name('File')->where('cate=0')->field('id,name,original')->page($page, 10)->select();

        return ajax_return($ret);
    }

}
